import React, {Component} from "react";
import {connect} from "react-redux";
import {SearchBarContainer, TypeButton} from "./style";
import {RightOutlined} from "@ant-design/icons";
import {getGameTypeList} from "@/api/JustGameType";
import {Col, Input, Row} from "antd";
import PropTypes from "prop-types";
import {getGamePlatformList} from "@/api/JustGamePlatform";
import {withRouter} from "react-router-dom";
import {getQueryVariable} from "@/util/global";
import {actions} from "@/common/header/store";

class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.handleSelectType = this.handleSelectType.bind(this);
        this.handleSearchInput = this.handleSearchInput.bind(this);
        this.handleSelectPlatform = this.handleSelectPlatform.bind(this);
        this.state = {
            gameTypes: [],
            platforms: [],
            selectTypes: new Set(),
            selectPlatforms: new Set(),
            searchValue: this.props.location.query ? this.props.location.query.kw : '',
        }
        this.props.handleClearSearchInfo();
    }

    handleSelectPlatform(platformId) {
        /* 仍从state中获取另一个选择项，然后传给onChange事件，这么做可解决无法双选的BUG */
        let {selectTypes, selectPlatforms, searchValue} = this.state;
        if (selectPlatforms.has(platformId)) {
            selectPlatforms.delete(platformId)
        } else {
            selectPlatforms.add(platformId);
        }
        this.props.onChange({selectTypes, selectPlatforms, searchValue});
        this.setState({
            selectPlatforms
        })
    }

    handleSelectType(typeId) {
        /* 仍从state中获取另一个选择项，然后传给onChange事件，这么做可解决无法双选的BUG */
        let {selectTypes, selectPlatforms, searchValue} = this.state;
        if (selectTypes.has(typeId)) {
            selectTypes.delete(typeId)
        } else {
            selectTypes.add(typeId);
        }
        this.props.onChange({selectTypes, selectPlatforms, searchValue});
        this.setState({
            selectTypes
        })
    }

    handleSearchInput() {
        let {selectTypes, selectPlatforms, searchValue} = this.state;
        this.props.onChange({selectTypes, selectPlatforms, searchValue});
    }

    componentDidMount() {
        getGameTypeList().then(response => {
            if (response.success) {
                let queryType = getQueryVariable('type');
                if (queryType) {
                    let findType = response.data.rows.find(type => {
                        return type['chineseName'].toLowerCase() === decodeURI(queryType).toLowerCase() ||
                            type['englishName'].toLowerCase() === decodeURI(queryType).toLowerCase();
                    });
                    if (findType) {
                        this.handleSelectType(findType.id)
                    }
                }
                this.setState({
                    gameTypes: response.data.rows,
                })
            }
        })
        getGamePlatformList().then(res => {
            if (res.success) {
                let queryPlatform = getQueryVariable('platform');
                if (queryPlatform) {
                    let findPlatform = res.data.rows.find(type => {
                        return type['name'].toLowerCase() === decodeURI(queryPlatform).toLowerCase();
                    });
                    if (findPlatform) {
                        this.handleSelectPlatform(findPlatform.id)
                    }
                }
                this.setState({
                    platforms: res.data.rows
                })
            }
        })
    }

    render() {
        return <>
            <SearchBarContainer>
                <Row gutter={[0, 0]}>
                    <Col span={24} style={{borderBottom: '1px dashed #b3b3b3'}}>
                        <div style={{float: 'left', padding: '0 5px 0 0'}}>
                            游戏类型<RightOutlined/>
                        </div>
                        <Row gutter={[16, 0]}>
                            {
                                this.state.gameTypes && this.state.gameTypes.length > 0 ?
                                    this.state.gameTypes.map((item, index) => {
                                        return <Col span={2} key={index}>
                                            <TypeButton onClick={() => this.handleSelectType(item.id)}>
                                        <span className={this.state.selectTypes.has(item.id) ? 'selected' : ''}>
                                            {item['chineseName']}
                                        </span>
                                            </TypeButton>
                                        </Col>
                                    })
                                    :
                                    null
                            }
                        </Row>
                    </Col>
                    <Col span={24} style={{borderBottom: '1px dashed #b3b3b3'}}>
                        <div style={{float: 'left', padding: '0 5px 0 0', userSelect: 'none'}}>
                            游戏平台<RightOutlined/>
                        </div>
                        <Row gutter={[8, 0]}>
                            {
                                this.state.platforms && this.state.platforms.length > 0 ?
                                    this.state.platforms.map((item) => {
                                        return <Col span={2} key={item.id}>
                                            <TypeButton onClick={() => this.handleSelectPlatform(item.id)}>
                                        <span className={this.state.selectPlatforms.has(item.id) ? 'selected' : ''}>
                                            {`${item['name']} ( ${item['version']} ) `}
                                        </span>
                                            </TypeButton>
                                        </Col>
                                    })
                                    :
                                    null
                            }
                        </Row>
                    </Col>
                    <Col span={24}>
                        <Row gutter={[16, 16]}>
                            <Col span={1.5}>
                                搜索关键字：
                            </Col>
                            <Col span={4}>
                                <Input width={100} value={this.state.searchValue}
                                       onChange={(e) => this.setState({searchValue: e.target.value})}
                                       onKeyDown={(e) => {
                                           if (e.key === 'Enter') {
                                               this.handleSearchInput()
                                           }
                                       }}
                                />
                            </Col>
                            <Col span={6}>

                            </Col>
                            <Col span={6}>

                            </Col>
                        </Row>
                    </Col>
                </Row>
            </SearchBarContainer>
        </>
    }
}

SearchBar.propTypes = {
    onChange: PropTypes.func
}
const mapState = (state) => {
    return {}
}
const mapDispatch = (dispatch) => {
    return {
        handleClearSearchInfo() {
            dispatch(actions.headerSearchInput(""))
        },
    }
}
export default connect(mapState, mapDispatch)(withRouter(SearchBar));
